﻿using System;

namespace HB.Base
{
    /// <summary>
    /// 可用于减少if else的嵌套结构，让代码变为平整，适用于多个判定条件的过程
    /// </summary>
    public class Checker
    {
        public bool CanContinue = true;
        public bool IsErr
        {
            get { return !CanContinue; }
        }
        public string Msg;
        /// <summary>
        /// 检查是否符合条件，如果已经发生错误，将不会再执行委托
        /// </summary>
        /// <param name="err">委托错误的提示</param>
        /// <param name="F">正确的情况委托</param>
        public bool Check(string err, Func<bool> F)
        {
            if (CanContinue)
            {
                CanContinue = F.Invoke();
                if (CanContinue == false)
                {
                    Msg = err;
                }
            }
            return CanContinue;
        }
        /// <summary>
        /// 检查是否符合条件，如果已经不符合条件，将不会再执行委托
        /// </summary>
        /// <param name="F">正确的情况委托</param>
        public bool Check(Func<bool> F)
        {
            if (CanContinue)
            {
                CanContinue = F.Invoke();
            }
            return CanContinue;
        }
        /// <summary>
        /// 检查各case中是否包含符合项
        /// </summary>
        /// <param name="err"></param>
        /// <param name="Fls"></param>
        /// <returns></returns>
        public bool CheckAny(string err, params Func<bool>[] Fls)
        {
            if (CanContinue)
            {
                foreach (var f in Fls)
                {
                    var temp = f.Invoke();
                    if (temp)//有一项符合即可停止
                    {
                        return true;
                    }
                }
                CanContinue = false;
                Msg = err;
            }
            return CanContinue;
        }
        /// <summary>
        /// 根据条件决定是否检查
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="err"></param>
        /// <param name="fls"></param>
        /// <returns></returns>
        public bool CheckIf(bool condition, string err, Func<bool> fls)
        {
            if (CanContinue)
            {
                if (condition)
                {
                    Check(err, fls);
                }
            }
            return CanContinue;
        }
        /// <summary>
        /// 根据条件决定是否检查
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="err"></param>
        /// <param name="fls"></param>
        /// <returns></returns>
        public bool CheckIfAny(bool condition, string err, params Func<bool>[] fls)
        {
            if (CanContinue)
            {
                if (condition)
                {
                    return CheckAny(err, fls);
                }
            }
            return CanContinue;
        }
    }
}
